import { Inject, Injectable } from '@nestjs/common';
import { CreatePersonDto } from './dto/create-person.dto';
import { UpdatePersonDto } from './dto/update-person.dto';
import { Neo4jService } from '../neo4j/neo4j.service';
import { Person } from './entities/person.entity';

@Injectable()
export class PersonService {
  @Inject(Neo4jService)
  private readonly neo4jService: Neo4jService;

  create(createPersonDto: CreatePersonDto) {
    const session = this.neo4jService.getDriver().session();
    return session.run(`
    CREATE (p:Person {
      id: randomUUID(),
      name: $name,
      lastname: $lastname,
      birthplace: $birthplace,
      birthdate: $birthdate,
      nationality: $nationality,
      address: $address
  })
  RETURN p`,{
    name: createPersonDto.name || null,
    lastname: createPersonDto.lastname || null,
    birthplace: createPersonDto.birthplace || null,
    birthdate: createPersonDto.birthdate || null,
    nationality: createPersonDto.nationality || null,
    address: createPersonDto.address || null
  }).then(res=>{
    return res.records[0].get('p')
  })
  
  }

  findAll() {
    const session = this.neo4jService.getDriver().session();
    return session.run(`MATCH (n:Person) RETURN n LIMIT 25`).then(res=>{
      const persons = res.records.map(row => {
        return new Person(
            row.get('n')
        )
    })
    return {persons};
    })
  }

  findOne(id: string) {
    const session = this.neo4jService.getDriver().session();
    return session.run(`MATCH (n:Person{id:$id}) RETURN n`,{id}).then(res=>{
      const person = res.records.map(row => {
        return new Person(
            row.get('n')
        )
    })
    return person;
    })
    }

  update(id: string, updatePersonDto: UpdatePersonDto) {
    const session = this.neo4jService.getDriver().session();
    return session.run(`
    MATCH (p:Person {
      id: $id
    }) SET p += $updatePersonDto
  RETURN p`,{
    id: id,
    updatePersonDto
  }).then(res=>{
    console.log(res)
    return res.records[0].get('p')
  })
  }

  remove(id: string) {
    const session = this.neo4jService.getDriver().session();
    return session.run(`
      MATCH (p:Person {
        id: $id
    }) 
    DETACH DELETE p
    RETURN p`,{
    id: id
  }).then(res=>{
    return res.records[0].get('p')
  })
  }
}
